<?php

namespace App\Http\Controllers\Api\Syj;

use App\Common\Responses;
use App\Http\Controllers\Controller;
use App\Models\House;
use App\Models\Store;
use App\Models\Syj\stores;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

class FindHouse extends Controller
{

    //房源经纬度转换
    public function store(Request $request){
        //表单数据
        $dopost = $request->except(['token', 'file']);
        //房源入库
        $model = House::addHouse($dopost);
        if ($model){
            return Responses::success($model,200,'success');
        }
        //发起http请求
        $client = new Client(['timeout'=>5]);
        //得到请求地址
        $url = config('gaode.geocode');
        $url = sprintf($url,$model->fang_add,$model->fang_province);
        //发起请求
        $response = $client->get($url);
        $body = $response->getBody();
        $arr = json_decode($body,true);
        //找到经纬度存入数据表中
        if(count($arr['geocode'])>0){
            $locationArr = explode(',',$arr['geocodes'][0]['location']);
            $model->update([
               'location'=>$locationArr[0],
                'latitude'=>$locationArr[1],
            ]);
        }
    }

    //新增
    public function add_house(Request $request){
        try {
            $data = $request->post();
            unset($data['_token']);
            //引用独立验证器
            //$validted = $request->validate($data);
            $param = Store::addStore($data);
            return Responses::success($param,20000,'success');
        }catch (\Exception $e){
            return Responses::error($e->getMessage());
        }
    }

    //删除
    public function del_house(Request $request){
        $id = $request->get('id');
        $data = Store::removeStore($id);
        return Responses::success($data,20000,'success');
    }

    //修改
    public function up_house(Request $request){
        $id = $request->get('id');
        $param = $request->post();
        unset($param['_token']);
        $data = Store::removeStore($id,$param);
        return Responses::success($data,200,'success');
    }

    //查看
    public function list_house(){
        //查询数据
        $data=Store::lookStores();
        return Responses::success($data,20000,'success');
    }
}
